function rois = autorois2(s,thres,N,plotting)

%rois = autorois1(path,filename,scann,thres,N) uses AP's autodetectroi.m to
%find the ROI indices

%INPUT:     s = scan-structure such as read in by scanread.m
%           N = parameter used for median and mean filters (NxN-mask, see
%               medfilt2 and filter 2 for details. Basically, larger N, more smoothness)
%       thres = threshold level of the noise.
%OUTPUT: structure 'rois' containing:
%        -indices: matrix indices of the defined ROI (to be used to sum over for obtaining the spectrum)
%        -data:    integrated scan using rois.indices
%        -datan:   integrated scan using rois.indices normalized by monitor
%                  from Specfile
%        -datae:   error (poisson counting)
%        -dataen:  normalized error
%        -cenom:   center of mask (Tuomas: 'more usefull for position than gaussian fit')

if nargin<4
    plotting = 0;
end

a = autodetectroi(log(sumx(s.A)),thres,N);

for i=1:length(a)
    rois(i).indices = find(a{i}==1);
end

%read in scan for instant plotting
for h=1:length(rois)
    for l=1:size(s.A,1)
        rois(h).data(l) = sumy(s.A(l,rois(h).indices));
        rois(h).datan(l) = sqrt(sumy(s.A(l,rois(h).indices)));
        rois(h).datae(l) = sumy(s.A(l,rois(h).indices))./s.monitor(l);
        rois(h).dataen(l) = sqrt(sumy(s.A(l,rois(h).indices)))./s.monitor(l);
    end
end

for n=1:length(rois)
    rois(n).cenom = trapz(s.energy_cc,rois(n).data'.*s.energy_cc)./trapz(s.energy_cc,rois(n).data');
end

if plotting
figure
    subplot(3,3,1)
        plot(s.energy_cc-rois(1).cenom,rois(1).datan)
        legend('ROI 1')
    subplot(3,3,2)
        plot(s.energy_cc-rois(2).cenom,rois(2).datan)
        legend('ROI 2')
    subplot(3,3,3)
        plot(s.energy_cc-rois(3).cenom,rois(3).datan)
        legend('ROI 3')
    subplot(3,3,4)
        plot(s.energy_cc-rois(4).cenom,rois(4).datan)
        legend('ROI 4')
    subplot(3,3,5)
        plot(s.energy_cc-rois(5).cenom,rois(5).datan)
        legend('ROI 5')
    subplot(3,3,6)
        plot(s.energy_cc-rois(6).cenom,rois(6).datan)
        legend('ROI 6')
    subplot(3,3,7)
        plot(s.energy_cc-rois(7).cenom,rois(7).datan)
        legend('ROI 7')
    subplot(3,3,8)
        plot(s.energy_cc-rois(8).cenom,rois(8).datan)
        legend('ROI 8')
    subplot(3,3,9)
        plot(s.energy_cc-rois(9).cenom,rois(9).datan)
        legend('ROI 9')
end